// 应用主逻辑
class RefundAuditApp {
    constructor() {
        this.currentUser = null;
        this.currentRefund = null;
        this.currentPage = 1;
        this.pageSize = 20;
        this.totalCount = 0;
        this.searchParams = {
            patientId: '',
            patientName: '',
            dateRange: 30,
            auditStatus: ''
        };
        this.init();
    }

    // 初始化应用
    init() {
        // 检查是否已登录
        if (apiClient.token) {
            this.showMainInterface();
            this.loadRefunds();
        } else {
            this.showLoginInterface();
        }

        // 绑定事件
        this.bindEvents();
    }

    // 绑定事件
    bindEvents() {
        // 登录表单提交
        document.getElementById('loginForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleLogin();
        });

        // 全局点击事件
        document.addEventListener('click', (e) => {
            if (e.target.id === 'logoutBtn') {
                this.logout();
            }
            if (e.target.id === 'refreshBtn') {
                this.loadRefunds();
            }
            if (e.target.id === 'searchBtn') {
                this.handleSearch();
            }
            if (e.target.id === 'resetBtn') {
                this.resetSearch();
            }
            if (e.target.id === 'backToListBtn') {
                this.showRefundList();
            }
            // 导航菜单点击
            if (e.target.closest('[data-section]')) {
                const section = e.target.closest('[data-section]').dataset.section;
                this.switchSection(section);
            }
        });

        // 分页大小改变
        document.addEventListener('change', (e) => {
            if (e.target.id === 'pageSizeSelect') {
                this.pageSize = parseInt(e.target.value);
                this.currentPage = 1;
                this.loadRefunds();
            }
            // 审核意见模板选择事件
            if (e.target.id === 'auditCommentTemplate') {
                const selectedTemplate = e.target.value;
                if (selectedTemplate) {
                    document.getElementById('auditComment').value = selectedTemplate;
                }
            }
        });

        // 新增审核意见按钮
        document.addEventListener('click', (e) => {
            if (e.target.id === 'addCommentBtn' || e.target.closest('#addCommentBtn')) {
                this.showCommentModal();
            }
            
            // 编辑审核意见
            if (e.target.classList.contains('edit-comment-btn')) {
                const commentId = e.target.dataset.commentId;
                const commentText = e.target.dataset.commentText;
                this.showCommentModal(commentId, commentText);
            }
            
            // 删除审核意见
            if (e.target.classList.contains('delete-comment-btn')) {
                const commentId = e.target.dataset.commentId;
                this.deleteAuditComment(commentId);
            }
            
            // 保存审核意见
            if (e.target.id === 'saveCommentBtn') {
                this.saveAuditComment();
            }
            
            // 统计报表相关事件
            if (e.target.id === 'generateStatsBtn') {
                this.generateStatistics();
            }
            if (e.target.id === 'resetStatsBtn') {
                this.resetStatistics();
            }
            if (e.target.id === 'exportStatsBtn') {
                this.exportStatistics();
            }
            
            // 统计详情查看
            if (e.target.classList.contains('view-stats-detail-btn')) {
                const refundId = e.target.dataset.refundId;
                this.viewRefundDetail(refundId);
            }
        });
    }

    // 显示登录界面
    showLoginInterface() {
        document.getElementById('loginContainer').style.display = 'flex';
        document.getElementById('mainContainer').style.display = 'none';
    }

    // 显示主界面
    showMainInterface() {
        document.getElementById('loginContainer').style.display = 'none';
        document.getElementById('mainContainer').style.display = 'block';
        
        // 显示用户信息
        if (this.currentUser) {
            document.getElementById('userInfo').textContent = `欢迎，${this.currentUser.username}`;
        }
    }

    // 处理登录
    async handleLogin() {
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        const loginBtn = document.getElementById('loginBtn');
        const loginSpinner = document.getElementById('loginSpinner');
        const loginError = document.getElementById('loginError');

        // 清除之前的错误信息
        loginError.textContent = '';

        // 显示加载状态
        loginBtn.disabled = true;
        loginSpinner.classList.remove('d-none');

        try {
            const response = await apiClient.login(username, password);
            console.log('登录响应:', response);
            
            // 检查登录是否成功
            console.log('检查响应对象:', response);
            console.log('Token值:', response?.token);
            
            if (response && response.token) {
                // 后端返回的字段都是小写
                this.currentUser = {
                    token: response.token,
                    username: response.username,
                    role: response.role,
                    expiresAt: response.expiresAt
                };
                console.log('登录成功，用户信息:', this.currentUser);
                this.showMainInterface();
                this.loadRefunds();
            } else {
                console.error('登录失败，响应中没有找到Token');
                throw new Error('登录失败，请检查用户名和密码');
            }
        } catch (error) {
            console.error('登录错误:', error);
            loginError.textContent = error.message;
        } finally {
            loginBtn.disabled = false;
            loginSpinner.classList.add('d-none');
        }
    }

    // 退出登录
    logout() {
        apiClient.clearToken();
        this.currentUser = null;
        this.currentRefund = null;
        this.showLoginInterface();
        
        // 清空表单
        document.getElementById('loginForm').reset();
        document.getElementById('loginError').textContent = '';
    }

    // 切换导航页面
    switchSection(sectionName) {
        // 更新导航菜单状态
        document.querySelectorAll('[data-section]').forEach(link => {
            link.classList.remove('active');
        });
        document.querySelector(`[data-section="${sectionName}"]`).classList.add('active');

        // 隐藏所有内容区域
        document.querySelectorAll('.content-section').forEach(section => {
            section.style.display = 'none';
        });

        // 显示对应的内容区域
        const targetSection = document.getElementById(sectionName + 'Section');
        if (targetSection) {
            targetSection.style.display = 'block';
        }
        
        // 特殊处理：切换到统计页面时初始化日期范围
        if (sectionName === 'statistics') {
            this.initStatisticsPage();
        }
        
        // 特殊处理：切换到审核意见维护页面时加载数据
        if (sectionName === 'auditComments') {
            this.loadAuditComments();
        }

        // 根据不同页面加载相应数据
        if (sectionName === 'audit') {
            this.loadRefunds();
        } else if (sectionName === 'auditComments') {
            this.loadAuditComments();
        }
    }

    // 处理搜索
    handleSearch() {
        this.searchParams.patientId = document.getElementById('searchPatientId').value.trim();
        this.searchParams.patientName = document.getElementById('searchPatientName').value.trim();
        this.searchParams.dateRange = parseInt(document.getElementById('searchDateRange').value);
        this.searchParams.auditStatus = document.getElementById('searchAuditStatus').value;
        
        this.currentPage = 1;
        this.loadRefunds();
    }

    // 重置搜索
    resetSearch() {
        document.getElementById('searchPatientId').value = '';
        document.getElementById('searchPatientName').value = '';
        document.getElementById('searchDateRange').value = '30';
        document.getElementById('searchAuditStatus').value = '';
        
        this.searchParams = {
            patientId: '',
            patientName: '',
            dateRange: 30,
            auditStatus: ''
        };
        
        this.currentPage = 1;
        this.loadRefunds();
    }

    // 加载退款申请列表
    async loadRefunds() {
        const loadingElement = document.getElementById('loadingRefunds');
        const listElement = document.getElementById('refundList');

        loadingElement.style.display = 'block';
        listElement.innerHTML = '';

        try {
            let response;
            
            // 根据搜索条件选择不同的API
            if (this.searchParams.patientId) {
                // 按患者ID和日期范围查询
                response = await apiClient.getRefundsByPatientIdAndDays(
                    this.searchParams.patientId, 
                    this.searchParams.dateRange
                );
            } else {
                // 获取所有退款申请
                response = await apiClient.getAllRefunds();
            }
            
            // 检查响应结构
            let refunds = [];
            if (response && response.data) {
                refunds = response.data;
            } else if (Array.isArray(response)) {
                refunds = response;
            } else {
                throw new Error('响应数据格式错误');
            }

            // 前端过滤（因为后端API有限）
            refunds = this.filterRefunds(refunds);
            
            // 分页处理
            this.totalCount = refunds.length;
            const startIndex = (this.currentPage - 1) * this.pageSize;
            const endIndex = startIndex + this.pageSize;
            const pagedRefunds = refunds.slice(startIndex, endIndex);
            
            this.renderRefundList(pagedRefunds);
            this.renderPagination();
            this.updateTotalCount();
            
        } catch (error) {
            // 如果是认证错误，自动跳转到登录页面
            if (error.message.includes('认证失败')) {
                this.logout();
                return;
            }
            
            listElement.innerHTML = `
                <div class="alert alert-danger">
                    <i class="bi bi-exclamation-triangle"></i>
                    加载退款申请失败: ${error.message}
                </div>
            `;
        } finally {
            loadingElement.style.display = 'none';
        }
    }

    // 前端过滤退款申请
    filterRefunds(refunds) {
        return refunds.filter(refund => {
            // 按患者姓名过滤
            if (this.searchParams.patientName && 
                !refund.patName.includes(this.searchParams.patientName)) {
                return false;
            }
            
            // 按审核状态过滤
            if (this.searchParams.auditStatus !== '') {
                const auditStatus = this.searchParams.auditStatus;
                if (auditStatus === '0' && (refund.auditResult === '0' || refund.auditResult === 0 || !refund.auditResult || refund.auditResult === '')) {
                    // 待审核状态匹配
                } else if (auditStatus === '1' && (refund.auditResult === '1' || refund.auditResult === 1)) {
                    // 审核通过状态匹配
                } else if (auditStatus === '2' && (refund.auditResult === '2' || refund.auditResult === 2)) {
                    // 审核失败状态匹配
                } else {
                    return false; // 状态不匹配
                }
            }
            
            // 按日期范围过滤（如果没有按患者ID查询）
            if (!this.searchParams.patientId && this.searchParams.dateRange) {
                const inputDate = new Date(refund.inputDate);
                const cutoffDate = new Date();
                cutoffDate.setDate(cutoffDate.getDate() - this.searchParams.dateRange);
                if (inputDate < cutoffDate) {
                    return false;
                }
            }
            
            return true;
        });
    }

    // 渲染退款申请列表
    renderRefundList(refunds) {
        const listElement = document.getElementById('refundList');
        
        if (!refunds || refunds.length === 0) {
            listElement.innerHTML = `
                <div class="alert alert-info text-center">
                    <i class="bi bi-info-circle"></i>
                    暂无退款申请记录
                </div>
            `;
            return;
        }

        const refundCards = refunds.map(refund => this.createRefundCard(refund)).join('');
        listElement.innerHTML = refundCards;
    }

    // 创建退款申请卡片
    createRefundCard(refund) {
        const statusClass = this.getStatusClass(refund.auditResult);
        const statusText = this.getStatusText(refund.auditResult);
        const inputDate = new Date(refund.inputDate).toLocaleString('zh-CN');
        const auditDate = refund.auditDate ? new Date(refund.auditDate).toLocaleString('zh-CN') : '未审核';

        return `
            <div class="refund-card card" onclick="app.showRefundDetail(${refund.id})">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-8">
                            <h6 class="card-title">
                                <i class="bi bi-person"></i>
                                ${refund.patName} (${refund.patientId})
                            </h6>
                            <p class="card-text text-muted mb-1">
                                <small>
                                    <i class="bi bi-calendar"></i> 申请时间: ${inputDate}
                                </small>
                            </p>
                            <p class="card-text text-muted mb-1">
                                <small>
                                    <i class="bi bi-telephone"></i> 联系电话: ${refund.phoneNumber}
                                </small>
                            </p>
                            <p class="card-text text-muted">
                                <small>
                                    <i class="bi bi-tag"></i> 退款类型: ${refund.refundTypeName}
                                </small>
                            </p>
                        </div>
                        <div class="col-md-4 text-end">
                            <div class="mb-2">
                                <span class="badge ${statusClass} status-badge">${statusText}</span>
                            </div>
                            <div class="mb-2">
                                <strong class="text-primary">¥${refund.refundAmount}</strong>
                            </div>
                            <div>
                                <small class="text-muted">
                                    审核时间: ${auditDate}
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    // 获取状态样式类
    getStatusClass(auditResult) {
        switch (auditResult) {
            case '1':
            case 1:
            case '通过':
            case '已通过':
                return 'bg-success';
            case '2':
            case 2:
            case '拒绝':
            case '已拒绝':
                return 'bg-danger';
            case '0':
            case 0:
            case '待审核':
            case null:
            case undefined:
            case '':
                return 'bg-warning';
            default:
                return 'bg-secondary';
        }
    }

    // 获取状态文本
    getStatusText(auditResult) {
        // 根据数据字典映射审核状态
        switch (auditResult) {
            case '0':
            case 0:
            case null:
            case undefined:
            case '':
                return '待审核';
            case '1':
            case 1:
                return '审核通过';
            case '2':
            case 2:
                return '审核失败';
            case '通过':
            case '已通过':
                return '审核通过';
            case '拒绝':
            case '已拒绝':
                return '审核失败';
            default:
                return auditResult;
        }
    }

    // 获取状态徽章
    getStatusBadge(auditStatus) {
        const statusText = this.getStatusText(auditStatus);
        let badgeClass = '';
        
        switch (auditStatus) {
            case '1':
            case 1:
            case '通过':
            case '已通过':
                badgeClass = 'badge bg-success';
                break;
            case '2':
            case 2:
            case '拒绝':
            case '已拒绝':
                badgeClass = 'badge bg-danger';
                break;
            case '0':
            case 0:
            case '待审核':
            case null:
            case undefined:
            case '':
                badgeClass = 'badge bg-warning';
                break;
            default:
                badgeClass = 'badge bg-secondary';
        }
        
        return `<span class="${badgeClass}">${statusText}</span>`;
    }

    // 格式化日期
    formatDate(dateString) {
        if (!dateString) return '-';
        
        try {
            const date = new Date(dateString);
            if (isNaN(date.getTime())) {
                return dateString; // 如果无法解析，返回原字符串
            }
            
            // 格式化为 YYYY-MM-DD HH:mm:ss
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        } catch (error) {
            console.error('日期格式化失败:', error, dateString);
            return dateString;
        }
    }

    // 更新总数显示
    updateTotalCount() {
        const totalCountElement = document.getElementById('totalCount');
        if (totalCountElement) {
            totalCountElement.textContent = `共 ${this.totalCount} 条记录`;
        }
    }

    // 渲染分页控件
    renderPagination() {
        const paginationElement = document.getElementById('pagination');
        if (!paginationElement) return;

        const totalPages = Math.ceil(this.totalCount / this.pageSize);
        if (totalPages <= 1) {
            paginationElement.innerHTML = '';
            return;
        }

        let paginationHtml = '';
        
        // 上一页按钮
        paginationHtml += `
            <li class="page-item ${this.currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${this.currentPage - 1}">上一页</a>
            </li>
        `;

        // 页码按钮
        const startPage = Math.max(1, this.currentPage - 2);
        const endPage = Math.min(totalPages, this.currentPage + 2);

        if (startPage > 1) {
            paginationHtml += `<li class="page-item"><a class="page-link" href="#" data-page="1">1</a></li>`;
            if (startPage > 2) {
                paginationHtml += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
            }
        }

        for (let i = startPage; i <= endPage; i++) {
            paginationHtml += `
                <li class="page-item ${i === this.currentPage ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>
            `;
        }

        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                paginationHtml += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
            }
            paginationHtml += `<li class="page-item"><a class="page-link" href="#" data-page="${totalPages}">${totalPages}</a></li>`;
        }

        // 下一页按钮
        paginationHtml += `
            <li class="page-item ${this.currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${this.currentPage + 1}">下一页</a>
            </li>
        `;

        paginationElement.innerHTML = paginationHtml;

        // 绑定分页点击事件
        paginationElement.addEventListener('click', (e) => {
            e.preventDefault();
            if (e.target.classList.contains('page-link') && e.target.dataset.page) {
                const page = parseInt(e.target.dataset.page);
                if (page !== this.currentPage && page >= 1 && page <= totalPages) {
                    this.currentPage = page;
                    this.loadRefunds();
                }
            }
        });
    }

    // 显示退款申请列表
    showRefundList() {
        document.getElementById('refundListView').style.display = 'block';
        document.getElementById('refundDetailView').style.display = 'none';
    }

    // 显示退款申请详情
    async showRefundDetail(refundId) {
        try {
            const refund = await apiClient.getRefundById(refundId);
            this.currentRefund = refund;
            this.renderRefundDetail(refund);
            
            // 切换视图
            document.getElementById('refundListView').style.display = 'none';
            document.getElementById('refundDetailView').style.display = 'block';
            
            // 加载审核意见模板
            await this.loadAuditCommentTemplates();
        } catch (error) {
            alert('加载退款申请详情失败: ' + error.message);
        }
    }

    // 渲染退款申请详情
    renderRefundDetail(refund) {
        const detailElement = document.getElementById('refundDetail');
        const inputDate = new Date(refund.inputDate).toLocaleString('zh-CN');
        const auditDate = refund.auditDate ? new Date(refund.auditDate).toLocaleString('zh-CN') : '未审核';
        const statusClass = this.getStatusClass(refund.auditResult);
        const statusText = this.getStatusText(refund.auditResult);

        // 渲染附件
        const attachmentsHtml = this.renderAttachments(refund.attachments || []);

        // 渲染代办人信息
        const agentInfoHtml = refund.publicAgentName ? `
            <div class="col-md-6">
                <h6><i class="bi bi-person-plus"></i> 代办人信息</h6>
                <p><strong>姓名:</strong> ${refund.publicAgentName}</p>
                <p><strong>电话:</strong> ${refund.publicAgentPhoneNumber || '未填写'}</p>
                <p><strong>关系:</strong> ${refund.publicAgentRelation || '未填写'}</p>
                <p><strong>银行:</strong> ${refund.publicAgentRefundBankName || '未填写'}</p>
                <p><strong>卡号:</strong> ${refund.publicAgentRefundBankCardNo || '未填写'}</p>
                <p><strong>开户行:</strong> ${refund.publicAgentRefundBankOpenName || '未填写'}</p>
                <p><strong>开户城市:</strong> ${refund.publicAgentRefundBankCity || '未填写'}</p>
            </div>
        ` : '';

        detailElement.innerHTML = `
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="bi bi-file-text"></i>
                        退款申请详情 #${refund.id}
                    </h5>
                    <span class="badge ${statusClass}">${statusText}</span>
                </div>
                <div class="card-body">
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <h6><i class="bi bi-person"></i> 患者信息</h6>
                            <p><strong>姓名:</strong> ${refund.patName}</p>
                            <p><strong>患者ID:</strong> ${refund.patientId}</p>
                            <p><strong>身份证号:</strong> ${refund.idNumber || '未填写'}</p>
                            <p><strong>联系电话:</strong> ${refund.phoneNumber}</p>
                            <p><strong>申请时间:</strong> ${inputDate}</p>
                            <p><strong>关联ID:</strong> ${refund.relId || '无'}</p>
                        </div>
                        <div class="col-md-6">
                            <h6><i class="bi bi-credit-card"></i> 退款信息</h6>
                            <p><strong>退款金额:</strong> <span class="text-primary">¥${refund.refundAmount}</span></p>
                            <p><strong>退款类型:</strong> ${refund.refundTypeName}</p>
                            <p><strong>银行名称:</strong> ${refund.refundBankName}</p>
                            <p><strong>银行卡号:</strong> ${refund.refundBankCardNo}</p>
                            <p><strong>开户行:</strong> ${refund.refundBankOpenName}</p>
                            <p><strong>开户城市:</strong> ${refund.refundBankCity}</p>
                        </div>
                    </div>
                    
                    ${agentInfoHtml ? `<div class="row mb-4">${agentInfoHtml}</div>` : ''}
                    
                    <div class="row mb-4">
                        <div class="col-12">
                            <h6><i class="bi bi-paperclip"></i> 附件信息</h6>
                            ${attachmentsHtml}
                        </div>
                    </div>
                    
                    <div class="row mb-4">
                        <div class="col-12">
                            <h6><i class="bi bi-clipboard-check"></i> 审核信息</h6>
                            <p><strong>审核状态:</strong> <span class="badge ${statusClass}">${statusText}</span></p>
                            <p><strong>审核人:</strong> ${refund.auditUserName || '未审核'}</p>
                            <p><strong>审核时间:</strong> ${auditDate}</p>
                            <p><strong>审核意见:</strong> ${refund.auditComment || '无'}</p>
                        </div>
                    </div>
                    
                    ${this.renderAuditSection(refund)}
                </div>
            </div>
        `;
    }

    // 渲染附件
    renderAttachments(attachments) {
        if (!attachments || attachments.length === 0) {
            return '<p class="text-muted">无附件</p>';
        }

        const html = attachments.map(attachment => {
            const loadingSvg = btoa(unescape(encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="150" height="150" viewBox="0 0 150 150"><rect width="150" height="150" fill="#f8f9fa" stroke="#dee2e6"/><text x="75" y="75" text-anchor="middle" dy=".3em" fill="#6c757d">加载中...</text></svg>')));
            const errorSvg = btoa(unescape(encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="150" height="150" viewBox="0 0 150 150"><rect width="150" height="150" fill="#f8f9fa" stroke="#dee2e6"/><text x="75" y="60" text-anchor="middle" dy=".3em" fill="#dc3545" font-size="12">加载失败</text><text x="75" y="90" text-anchor="middle" dy=".3em" fill="#6c757d" font-size="10">点击重试</text></svg>')));
            
            const previewHtml = attachment.filePaths ? `
                <img src="data:image/svg+xml;base64,${loadingSvg}"
                     class="attachment-preview" 
                     data-file-path="${attachment.filePaths}"
                     onclick="app.previewAttachment('${attachment.filePaths}')"
                     onerror="this.src='data:image/svg+xml;base64,${errorSvg}'">
            ` : '<span class="text-muted">无文件</span>';
            
            return `
                <div class="d-inline-block m-2 text-center">
                    ${previewHtml}
                    <div class="mt-1">
                        <small class="text-muted">${attachment.attachName}</small>
                    </div>
                </div>
            `;
        }).join('');
        
        // 延迟加载真实图片
        setTimeout(() => this.loadAttachmentPreviews(), 100);
        
        return html;
    }
    
    // 加载附件预览图片
    async loadAttachmentPreviews() {
        const previewImages = document.querySelectorAll('.attachment-preview[data-file-path]');
        console.log('开始加载附件预览，找到图片数量:', previewImages.length);
        
        for (const img of previewImages) {
            const filePath = img.getAttribute('data-file-path');
            console.log('正在加载附件:', filePath);
            
            if (filePath) {
                try {
                    console.log('调用 getFileByPath API:', filePath);
                    const blob = await apiClient.getFileByPath(filePath);
                    console.log('API 返回 blob:', blob, 'blob大小:', blob?.size, 'blob类型:', blob?.type);
                    
                    if (blob && blob.size > 0) {
                        const imageUrl = URL.createObjectURL(blob);
                        console.log('创建图片URL:', imageUrl);
                        img.src = imageUrl;
                        
                        // 当图片不再需要时释放URL
                        img.addEventListener('load', () => {
                            console.log('图片加载成功:', filePath);
                            setTimeout(() => URL.revokeObjectURL(imageUrl), 1000);
                        });
                        
                        img.addEventListener('error', () => {
                            console.error('图片显示失败:', filePath, '图片URL:', imageUrl);
                        });
                    } else {
                        console.error('获取到的blob无效:', filePath, blob);
                    }
                } catch (error) {
                    console.error('加载附件预览失败:', filePath, error);
                    console.error('错误详情:', error.message, error.stack);
                    // 保持错误状态的SVG
                }
            } else {
                console.warn('图片元素缺少文件路径属性');
            }
        }
    }

    // 渲染审核区域
    renderAuditSection(refund) {
        // 如果已经审核过，不显示审核区域
        // 只有状态为'0'、0、null、undefined、''或'待审核'时才显示审核区域
        if (refund.auditResult === '1' || refund.auditResult === 1 || 
            refund.auditResult === '2' || refund.auditResult === 2 ||
            (refund.auditResult && refund.auditResult !== '0' && refund.auditResult !== '待审核')) {
            return '';
        }

        return `
            <div class="audit-section">
                <h6><i class="bi bi-clipboard-check"></i> 审核操作</h6>
                <form id="auditForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">审核结果</label>
                                <select class="form-select" id="auditResult" required>
                                    <option value="">请选择审核结果</option>
                                    <option value="1">通过</option>
                                    <option value="2">拒绝</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">审核人</label>
                                <input type="text" class="form-control" id="auditUser" 
                                       value="${this.currentUser?.username || ''}" required>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">审核意见模板</label>
                        <select class="form-select" id="auditCommentTemplate">
                            <option value="">请选择审核意见模板（可选）</option>
                        </select>
                        <small class="form-text text-muted">选择模板后会自动填入审核意见框</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">审核意见 <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="auditComment" rows="3" 
                                  placeholder="请输入审核意见..." required></textarea>
                    </div>
                    <div class="text-end">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check-circle"></i> 提交审核
                        </button>
                    </div>
                </form>
            </div>
        `;
    }

    // 加载审核意见模板
    async loadAuditCommentTemplates() {
        try {
            const templates = await apiClient.getDictByDictId(5);
            const templateSelect = document.getElementById('auditCommentTemplate');
            
            if (templateSelect && templates) {
                // 清空现有选项（保留默认选项）
                templateSelect.innerHTML = '<option value="">请选择审核意见模板（可选）</option>';
                
                // 添加模板选项
                templates.forEach(template => {
                    const option = document.createElement('option');
                    option.value = template.itemName;
                    option.textContent = template.itemName;
                    templateSelect.appendChild(option);
                });
            }
        } catch (error) {
            console.error('加载审核意见模板失败:', error);
        }
    }

    // 加载审核意见列表
    async loadAuditComments() {
        try {
            const comments = await apiClient.getDictByDictId(5);
            this.renderAuditComments(comments || []);
        } catch (error) {
            console.error('加载审核意见失败:', error);
            alert('加载审核意见失败: ' + error.message);
        }
    }

    // 渲染审核意见列表
    renderAuditComments(comments) {
        const tbody = document.getElementById('auditCommentsTableBody');
        if (!tbody) return;

        if (comments.length === 0) {
            tbody.innerHTML = '<tr><td colspan="4" class="text-center text-muted">暂无审核意见</td></tr>';
            return;
        }

        tbody.innerHTML = comments.map((comment, index) => `
            <tr>
                <td>${index + 1}</td>
                <td>${comment.itemName}</td>
                <td>${new Date(comment.inputDate).toLocaleString()}</td>
                <td>
                    <button type="button" class="btn btn-sm btn-outline-primary me-2 edit-comment-btn" 
                            data-comment-id="${comment.id}" data-comment-text="${comment.itemName}">
                        <i class="bi bi-pencil"></i> 编辑
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-danger delete-comment-btn" 
                            data-comment-id="${comment.id}">
                        <i class="bi bi-trash"></i> 删除
                    </button>
                </td>
            </tr>
        `).join('');
    }

    // 显示审核意见编辑模态框
    showCommentModal(commentId = null, commentText = '') {
        const modal = new bootstrap.Modal(document.getElementById('commentModal'));
        const modalTitle = document.getElementById('commentModalTitle');
        const commentTextArea = document.getElementById('commentText');
        const saveBtn = document.getElementById('saveCommentBtn');

        if (commentId) {
            modalTitle.textContent = '编辑审核意见';
            commentTextArea.value = commentText;
            saveBtn.dataset.commentId = commentId;
        } else {
            modalTitle.textContent = '新增审核意见';
            commentTextArea.value = '';
            delete saveBtn.dataset.commentId;
        }

        modal.show();
    }

    // 保存审核意见
    async saveAuditComment() {
        const commentText = document.getElementById('commentText').value.trim();
        const saveBtn = document.getElementById('saveCommentBtn');
        const commentId = saveBtn.dataset.commentId;

        if (!commentText) {
            alert('请输入审核意见内容');
            return;
        }

        console.log('开始保存审核意见:', { commentId, commentText });

        try {
            if (commentId) {
                // 编辑现有审核意见
                const existingComments = await apiClient.getDictByDictId(5);
                const existingComment = existingComments.find(c => c.id == commentId);
                
                const updateData = {
                    DictId: 5,
                    DictName: '审核意见',
                    ItemName: commentText,
                    ItemValue: existingComment ? String(existingComment.itemValue) : '1'
                };
                
                console.log('更新数据:', updateData);
                const result = await apiClient.updateDict(parseInt(commentId), updateData);
                console.log('更新结果:', result);
                alert('审核意见更新成功');
            } else {
                // 新增审核意见
                const existingComments = await apiClient.getDictByDictId(5);
                const maxItemValue = existingComments.length > 0 
                    ? Math.max(...existingComments.map(c => parseInt(c.itemValue) || 0))
                    : 0;
                
                const createData = {
                    DictId: 5,
                    DictName: '审核意见',
                    ItemName: commentText,
                    ItemValue: String(maxItemValue + 1)
                };
                
                console.log('创建数据:', createData);
                const result = await apiClient.createDict(createData);
                console.log('创建结果:', result);
                alert('审核意见添加成功');
            }

            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('commentModal'));
            modal.hide();

            // 重新加载审核意见列表
            await this.loadAuditComments();
        } catch (error) {
            console.error('保存失败:', error);
            if (error.response) {
                console.error('响应状态:', error.response.status);
                console.error('响应数据:', error.response.data);
            }
            alert('保存审核意见失败: ' + (error.response?.data?.message || error.message));
        }
    }

    // 删除审核意见
    async deleteAuditComment(commentId) {
        if (!confirm('确定要删除这条审核意见吗？')) {
            return;
        }

        try {
            await apiClient.deleteDict(commentId);
            alert('审核意见删除成功');
            await this.loadAuditComments();
        } catch (error) {
            console.error('删除审核意见失败:', error);
            alert('删除审核意见失败: ' + error.message);
        }
    }

    // 预览附件
    async previewAttachment(filePath) {
        try {
            const blob = await apiClient.getFileByPath(filePath);
            const imageUrl = URL.createObjectURL(blob);
            
            const modalImage = document.getElementById('modalImage');
            modalImage.src = imageUrl;
            
            const imageModal = new bootstrap.Modal(document.getElementById('imageModal'));
            imageModal.show();
            
            // 模态框关闭时释放URL
            document.getElementById('imageModal').addEventListener('hidden.bs.modal', () => {
                URL.revokeObjectURL(imageUrl);
            }, { once: true });
        } catch (error) {
            alert('预览附件失败: ' + error.message);
        }
    }

    // 显示退款申请列表
    showRefundList() {
        document.getElementById('refundDetailView').style.display = 'none';
        document.getElementById('refundListView').style.display = 'block';
        this.currentRefund = null;
    }

    // 提交审核
    async submitAudit(event) {
        event.preventDefault();
        
        if (!this.currentRefund) {
            alert('当前没有选中的退款申请');
            return;
        }

        const auditResult = document.getElementById('auditResult').value;
        const auditUser = document.getElementById('auditUser').value;
        const auditComment = document.getElementById('auditComment').value.trim();

        if (!auditResult || !auditUser) {
            alert('请填写完整的审核信息');
            return;
        }

        if (!auditComment) {
            alert('审核意见不能为空，请填写审核意见');
            return;
        }

        try {
            const auditData = {
                AuditResult: auditResult,
                AuditUserName: auditUser,
                AuditComment: auditComment,
                AuditDate: new Date().toISOString()
            };

            await apiClient.auditRefund(this.currentRefund.id, auditData);
            alert('审核提交成功');
            
            // 刷新详情
            await this.showRefundDetail(this.currentRefund.id);
        } catch (error) {
            alert('审核提交失败: ' + error.message);
        }
    }

    // 统计报表相关方法
    
    // 生成统计报表
    async generateStatistics() {
        const startDate = document.getElementById('statsStartDate').value;
        const endDate = document.getElementById('statsEndDate').value;
        const auditStatus = document.getElementById('statsAuditStatus').value;
        const applicantType = document.getElementById('statsApplicantType').value;
        
        // 验证日期范围
        if (!startDate || !endDate) {
            alert('请选择开始日期和结束日期');
            return;
        }
        
        if (new Date(startDate) > new Date(endDate)) {
            alert('开始日期不能大于结束日期');
            return;
        }
        
        // 显示加载状态
        document.getElementById('loadingStats').style.display = 'block';
        document.getElementById('statsOverview').style.display = 'none';
        document.getElementById('statsDetailCard').style.display = 'none';
        
        try {
            // 构建查询参数
            const params = {
                startDate: startDate,
                endDate: endDate,
                auditStatus: auditStatus || null,
                applicantType: applicantType || null,
                pageIndex: 1,
                pageSize: 1000 // 获取所有数据用于统计
            };
            
            console.log('统计查询参数:', params);
            
            // 调用API获取数据
            const response = await apiClient.getRefunds(params);
            console.log('统计数据响应:', response);
            
            if (response && response.data) {
                this.renderStatistics(response.data, response.totalCount || 0, response.summary);
            } else {
                throw new Error('获取统计数据失败');
            }
        } catch (error) {
            console.error('生成统计失败:', error);
            alert('生成统计失败: ' + error.message);
        } finally {
            document.getElementById('loadingStats').style.display = 'none';
        }
    }
    
    // 渲染统计结果
    renderStatistics(data, totalCount, summary = null) {
        // 使用后端返回的统计概览数据，如果没有则使用前端计算
        let stats;
        if (summary) {
            stats = {
                total: summary.totalApplications,
                approved: summary.approvedCount,
                rejected: summary.rejectedCount,
                pending: summary.pendingCount
            };
        } else {
            // 兼容旧版本，使用前端计算
            stats = {
                total: totalCount,
                approved: data.filter(item => item.auditResult === '1' || item.auditResult === 1).length,
                rejected: data.filter(item => item.auditResult === '2' || item.auditResult === 2).length,
                pending: data.filter(item => item.auditResult === '0' || item.auditResult === 0 || !item.auditResult || item.auditResult === '').length
            };
        }
        
        // 更新概览卡片
        document.getElementById('totalApplications').textContent = stats.total;
        document.getElementById('approvedApplications').textContent = stats.approved;
        document.getElementById('rejectedApplications').textContent = stats.rejected;
        document.getElementById('pendingApplications').textContent = stats.pending;
        
        // 如果有金额统计，也可以在控制台显示
        if (summary && summary.totalRefundAmount !== undefined) {
            console.log('总退款金额:', summary.totalRefundAmount);
            console.log('已通过退款金额:', summary.approvedRefundAmount);
        }
        
        // 显示概览
        document.getElementById('statsOverview').style.display = 'flex';
        
        // 渲染详细列表
        this.renderStatisticsDetail(data);
        
        // 显示详细列表
        document.getElementById('statsDetailCard').style.display = 'block';
        document.getElementById('statsCount').textContent = `共 ${totalCount} 条记录`;
    }
    
    // 渲染统计详细列表
    renderStatisticsDetail(data) {
        const tbody = document.getElementById('statsDetailTableBody');
        
        if (!data || data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">暂无数据</td></tr>';
            return;
        }
        
        tbody.innerHTML = data.map(item => {
            // 修正：使用 auditResult 而不是 auditStatus
            const statusBadge = this.getStatusBadge(item.auditResult);
            // 修正：根据 PublicAgentName 是否存在判断是否为代办人申请
            const applicantType = item.publicAgentName ? '代办人申请' : '本人申请';
            // 修正：使用 auditUserName 而不是 auditUser
            const auditUser = item.auditUserName || '-';
            
            return `
                <tr>
                    <td>${item.id}</td>
                    <td>${item.patName || '-'}</td>
                    <td>¥${(item.refundAmount || 0).toFixed(2)}</td>
                    <td>${this.formatDate(item.inputDate)}</td>
                    <td>${statusBadge}</td>
                    <td>${applicantType}</td>
                    <td>${auditUser}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary view-stats-detail-btn" 
                                data-refund-id="${item.id}">
                            <i class="bi bi-eye"></i> 详情
                        </button>
                    </td>
                </tr>
            `;
        }).join('');
    }
    
    // 重置统计条件
    resetStatistics() {
        // 重置表单
        document.getElementById('statsStartDate').value = '';
        document.getElementById('statsEndDate').value = '';
        document.getElementById('statsAuditStatus').value = '';
        document.getElementById('statsApplicantType').value = '';
        
        // 隐藏统计结果
        document.getElementById('statsOverview').style.display = 'none';
        document.getElementById('statsDetailCard').style.display = 'none';
        
        // 设置默认日期范围（最近30天）
        const endDate = new Date();
        const startDate = new Date();
        startDate.setDate(endDate.getDate() - 30);
        
        document.getElementById('statsStartDate').value = startDate.toISOString().split('T')[0];
        document.getElementById('statsEndDate').value = endDate.toISOString().split('T')[0];
    }
    
    // 导出统计数据到Excel
    async exportStatistics() {
        const startDate = document.getElementById('statsStartDate').value;
        const endDate = document.getElementById('statsEndDate').value;
        const auditStatus = document.getElementById('statsAuditStatus').value;
        const applicantType = document.getElementById('statsApplicantType').value;
        
        if (!startDate || !endDate) {
            alert('请先生成统计数据');
            return;
        }
        
        try {
            // 构建查询参数
            const params = {
                startDate: startDate,
                endDate: endDate,
                auditStatus: auditStatus || null,
                applicantType: applicantType || null,
                pageIndex: 1,
                pageSize: 10000 // 获取所有数据
            };
            
            console.log('导出查询参数:', params);
            
            // 获取数据
            const response = await apiClient.getRefunds(params);
            
            if (response && response.data) {
                this.downloadExcel(response.data, startDate, endDate);
            } else {
                throw new Error('获取导出数据失败');
            }
        } catch (error) {
            console.error('导出失败:', error);
            alert('导出失败: ' + error.message);
        }
    }
    
    // 下载Excel文件
    downloadExcel(data, startDate, endDate) {
        // 构建CSV内容
        const headers = ['申请ID', '患者姓名', '申请金额', '申请日期', '审核状态', '申请人类型', '审核人', '审核时间', '审核意见'];
        const csvContent = [headers.join(',')];
        
        data.forEach(item => {
            const row = [
                item.id,
                `"${item.patientName || '-'}"`,
                (item.refundAmount || 0).toFixed(2),
                this.formatDate(item.createTime),
                this.getStatusText(item.auditStatus),
                item.isProxy ? '代办人申请' : '本人申请',
                `"${item.auditUser || '-'}"`,
                item.auditTime ? this.formatDate(item.auditTime) : '-',
                `"${item.auditComment || '-'}"`
            ];
            csvContent.push(row.join(','));
        });
        
        // 创建并下载文件
        const csvString = '\uFEFF' + csvContent.join('\n'); // 添加BOM以支持中文
        const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        
        if (link.download !== undefined) {
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', `退款申请统计_${startDate}_${endDate}.csv`);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
    
    // 获取状态文本
     getStatusText(status) {
         switch (status) {
             case '0': return '待审核';
             case '1': return '审核通过';
             case '2': return '审核失败';
             default: return '未知状态';
         }
     }
     
     // 初始化统计页面
     initStatisticsPage() {
         // 检查是否已经设置了日期，如果没有则设置默认值
         const startDateInput = document.getElementById('statsStartDate');
         const endDateInput = document.getElementById('statsEndDate');
         
         if (!startDateInput.value || !endDateInput.value) {
             // 设置默认日期范围（最近30天）
             const endDate = new Date();
             const startDate = new Date();
             startDate.setDate(endDate.getDate() - 30);
             
             startDateInput.value = startDate.toISOString().split('T')[0];
             endDateInput.value = endDate.toISOString().split('T')[0];
         }
     }
     
     // 查看退款申请详情
     async viewRefundDetail(refundId) {
         try {
             console.log('查看退款详情，ID:', refundId);
             
             // 获取退款详情
             const refund = await apiClient.getRefundById(refundId);
             if (!refund) {
                 alert('获取退款详情失败');
                 return;
             }
             
             // 获取患者信息
             let patientInfo = null;
             if (refund.patientId) {
                 try {
                     patientInfo = await apiClient.getPatientInfo(refund.patientId);
                 } catch (error) {
                     console.warn('获取患者信息失败:', error);
                 }
             }
             
             // 构建详情HTML
             const detailHtml = this.buildRefundDetailHtml(refund, patientInfo);
             
             // 显示详情弹窗
             this.showDetailModal(detailHtml);
             
         } catch (error) {
             console.error('查看退款详情失败:', error);
             alert('查看退款详情失败: ' + (error.message || '未知错误'));
         }
     }
     
     // 构建退款详情HTML
     buildRefundDetailHtml(refund, patientInfo) {
         const statusText = this.getStatusText(refund.auditStatus);
         const statusClass = refund.auditStatus === 1 ? 'success' : refund.auditStatus === 2 ? 'danger' : 'warning';
         
         let attachmentsHtml = '';
         if (refund.attachments && refund.attachments.length > 0) {
             attachmentsHtml = `
                 <div class="detail-section">
                     <h6>附件信息</h6>
                     <div class="attachments-grid">
                         ${refund.attachments.map(attachment => `
                             <div class="attachment-item">
                                 <img src="" 
                                      class="attachment-preview" 
                                      onclick="app.previewAttachment('${attachment.filePath}')" 
                                      style="width: 100px; height: 100px; object-fit: cover; cursor: pointer; border: 1px solid #ddd; border-radius: 4px;" 
                                      title="点击查看大图">
                                 <p class="attachment-name">${attachment.fileName || '附件'}</p>
                             </div>
                         `).join('')}
                     </div>
                 </div>
             `;
         }
         
         // 判断是否为代办人申请
         const isProxy = refund.publicAgentName || refund.isProxy;
         
         // 代办人信息HTML
         const agentInfoHtml = isProxy && refund.publicAgentName ? `
             <div class="detail-section">
                 <h6>代办人信息</h6>
                 <div class="row">
                     <div class="col-md-6">
                         <p><strong>姓名:</strong> ${refund.publicAgentName}</p>
                         <p><strong>电话:</strong> ${refund.publicAgentPhoneNumber || '-'}</p>
                         <p><strong>关系:</strong> ${refund.publicAgentRelation || '-'}</p>
                     </div>
                     <div class="col-md-6">
                         <p><strong>银行:</strong> ${refund.publicAgentRefundBankName || '-'}</p>
                         <p><strong>卡号:</strong> ${refund.publicAgentRefundBankCardNo || '-'}</p>
                         <p><strong>开户行:</strong> ${refund.publicAgentRefundBankOpenName || '-'}</p>
                         <p><strong>开户城市:</strong> ${refund.publicAgentRefundBankCity || '-'}</p>
                     </div>
                 </div>
             </div>
         ` : '';
         
         // 银行信息HTML（本人申请时显示）
         const bankInfoHtml = !isProxy ? `
             <div class="detail-section">
                 <h6>银行信息</h6>
                 <div class="row">
                     <div class="col-md-6">
                         <p><strong>银行名称:</strong> ${refund.refundBankName || '-'}</p>
                         <p><strong>银行卡号:</strong> ${refund.refundBankCardNo || '-'}</p>
                     </div>
                     <div class="col-md-6">
                         <p><strong>开户行:</strong> ${refund.refundBankOpenName || '-'}</p>
                         <p><strong>开户城市:</strong> ${refund.refundBankCity || '-'}</p>
                     </div>
                 </div>
             </div>
         ` : '';
         
         return `
             <div class="refund-detail">
                 <div class="detail-header">
                     <h5>退款申请详情</h5>
                     <span class="badge badge-${statusClass}">${statusText}</span>
                 </div>
                 
                 <div class="detail-section">
                     <h6>基本信息</h6>
                     <div class="row">
                         <div class="col-md-6">
                             <p><strong>申请ID:</strong> ${refund.id}</p>
                             <p><strong>患者ID:</strong> ${refund.patientId || '-'}</p>
                             <p><strong>患者姓名:</strong> ${refund.patName || refund.patientName || '-'}</p>
                             <p><strong>退款金额:</strong> ¥${(refund.refundAmount || 0).toFixed(2)}</p>
                         </div>
                         <div class="col-md-6">
                             <p><strong>申请时间:</strong> ${this.formatDate(refund.inputDate)}</p>
                             <p><strong>申请类型:</strong> ${isProxy ? '代办人申请' : '本人申请'}</p>
                             <p><strong>退款类型:</strong> ${refund.refundTypeName || '-'}</p>
                             <p><strong>申请原因:</strong> ${refund.refundReason || '-'}</p>
                         </div>
                     </div>
                 </div>
                 
                 ${patientInfo ? `
                 <div class="detail-section">
                     <h6>患者信息</h6>
                     <div class="row">
                         <div class="col-md-6">
                             <p><strong>姓名:</strong> ${patientInfo.name || refund.patName || '-'}</p>
                             <p><strong>性别:</strong> ${patientInfo.gender || '-'}</p>
                             <p><strong>年龄:</strong> ${patientInfo.age || '-'}</p>
                         </div>
                         <div class="col-md-6">
                             <p><strong>电话:</strong> ${patientInfo.phone || refund.phoneNumber || '-'}</p>
                             <p><strong>身份证:</strong> ${patientInfo.idCard || refund.idNumber || '-'}</p>
                         </div>
                     </div>
                 </div>
                 ` : ''}
                 
                 ${agentInfoHtml}
                 
                 ${bankInfoHtml}
                 
                 <div class="detail-section">
                     <h6>审核信息</h6>
                     <div class="row">
                         <div class="col-md-6">
                             <p><strong>审核状态:</strong> <span class="badge badge-${statusClass}">${statusText}</span></p>
                             <p><strong>审核人:</strong> ${refund.auditUser || refund.auditUserName || '-'}</p>
                         </div>
                         <div class="col-md-6">
                             <p><strong>审核时间:</strong> ${refund.auditTime ? this.formatDate(refund.auditTime) : '-'}</p>
                         </div>
                     </div>
                     ${refund.auditComment ? `<p><strong>审核意见:</strong> ${refund.auditComment}</p>` : ''}
                 </div>
                 
                 ${attachmentsHtml}
             </div>
         `;
     }
     
     // 显示详情弹窗
     showDetailModal(content) {
         // 创建模态框
         const modalHtml = `
             <div class="modal fade" id="refundDetailModal" tabindex="-1" role="dialog">
                 <div class="modal-dialog modal-lg" role="document">
                     <div class="modal-content">
                         <div class="modal-header">
                             <h5 class="modal-title">退款申请详情</h5>
                             <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                         </div>
                         <div class="modal-body">
                             ${content}
                         </div>
                         <div class="modal-footer">
                             <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                         </div>
                     </div>
                 </div>
             </div>
         `;
         
         // 移除已存在的模态框
         const existingModal = document.getElementById('refundDetailModal');
         if (existingModal) {
             existingModal.remove();
         }
         
         // 添加新的模态框
         document.body.insertAdjacentHTML('beforeend', modalHtml);
         
         // 显示模态框 - 使用原生JavaScript
         const modal = document.getElementById('refundDetailModal');
         const bootstrapModal = new bootstrap.Modal(modal);
         bootstrapModal.show();
         
         // 模态框关闭后移除DOM - 使用原生JavaScript
         modal.addEventListener('hidden.bs.modal', function () {
             modal.remove();
         });
         
         // 延迟加载附件图片
         setTimeout(() => {
             this.loadAttachmentImages();
         }, 100);
     }
     
     // 加载附件图片
     async loadAttachmentImages() {
         const images = document.querySelectorAll('#refundDetailModal .attachment-preview');
         for (const img of images) {
             const filePath = img.getAttribute('onclick')?.match(/'([^']+)'/)?.[1];
             if (filePath && img.src.includes('data:image/svg+xml')) {
                 try {
                     const blob = await apiClient.getFileByPath(filePath);
                     const imageUrl = URL.createObjectURL(blob);
                     img.src = imageUrl;
                     
                     // 图片加载完成后释放之前的URL
                     img.onload = () => {
                         if (img.dataset.oldUrl) {
                             URL.revokeObjectURL(img.dataset.oldUrl);
                         }
                     };
                     img.dataset.oldUrl = imageUrl;
                 } catch (error) {
                     console.error('加载附件图片失败:', error);
                     img.src = '';
                 }
             }
         }
     }
 }

// 创建应用实例
const app = new RefundAuditApp();

// 全局函数
function logout() {
    app.logout();
}

function loadRefunds() {
    app.loadRefunds();
}

function showRefundList() {
    app.showRefundList();
}

// 绑定审核表单提交事件
document.addEventListener('submit', (e) => {
    if (e.target.id === 'auditForm') {
        app.submitAudit(e);
    }
});

// 动态加载附件图片
document.addEventListener('DOMContentLoaded', () => {
    // 延迟加载附件图片
    const loadAttachmentImages = () => {
        const images = document.querySelectorAll('.attachment-preview');
        images.forEach(async (img) => {
            const filePath = img.getAttribute('onclick')?.match(/'([^']+)'/)?.[1];
            if (filePath && img.src.includes('data:image/svg+xml')) {
                try {
                    const blob = await apiClient.getFileByPath(filePath);
                    const imageUrl = URL.createObjectURL(blob);
                    img.src = imageUrl;
                    
                    // 图片加载完成后释放之前的URL
                    img.onload = () => {
                        if (img.dataset.oldUrl) {
                            URL.revokeObjectURL(img.dataset.oldUrl);
                        }
                    };
                    img.dataset.oldUrl = imageUrl;
                } catch (error) {
                    console.error('加载附件图片失败:', error);
                }
            }
        });
    };

    // 监听DOM变化，自动加载新的附件图片
    const observer = new MutationObserver(() => {
        loadAttachmentImages();
    });
    
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
});